package com.szmmsoft.mp.common.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWTPayload;
import com.szmmsoft.mp.common.constant.CacheConstants;
import com.szmmsoft.mp.common.constant.Constants;
import com.szmmsoft.mp.common.exception.BusinessException;
import com.szmmsoft.mp.common.until.JWTUtil;
import com.szmmsoft.mp.common.until.LoginUtil;
import com.szmmsoft.mp.common.until.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * Description of the class.
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-15
 */
@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AuthInterceptor");
        //options预检
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String token = request.getHeader(Constants.TOKEN);
        if (CharSequenceUtil.isEmpty(token)) {
            throw new BusinessException("token不可为空");
        }
        JWTPayload jwtPayload = JWTUtil.getPayLoad(token);
        Long uid = Long.parseLong((String) jwtPayload.getClaim(JWTUtil.JWT_UID));
        String cacheKey = String.format(CacheConstants.LOGIN_USER, uid);
        if (!RedisUtils.exists(cacheKey)) {
            throw new BusinessException("登录过期请重新登陆");
        }
        String redisToken = RedisUtils.get(cacheKey);
        if (!token.equals(redisToken)) {
            throw new BusinessException("用户校验失败");
        }
        //提前一天续期
        if (RedisUtils.getTimeToLive(cacheKey) < JWTUtil.JWT_HEAD_REFRESH_TIME) {
            log.info("用户{}开始续期需求成功", uid);
            RedisUtils.set(cacheKey,token, Duration.ofMillis(JWTUtil.JWT_EXPIRE_TIME));
        }
        LoginUtil.set(uid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUtil.clear();
    }

    public static void main(String[] args) {

    }
}
